<template>
  <div class="product-manage">
    <div class="toolbar">
      <el-button type="primary" @click="openAdd">添加商品</el-button>
    </div>

    <el-table :data="productList" stripe v-loading="loading">
      <el-table-column label="图片" width="100">
        <template #default="{ row }">
          <el-image :src="resolveImage(row.image)" fit="cover" style="width:64px;height:64px;border-radius:6px"/>
        </template>
      </el-table-column>
      <el-table-column prop="productId" label="ID" width="80"/>
      <el-table-column prop="name" label="名称" min-width="200" show-overflow-tooltip/>
      <el-table-column prop="price" label="价格" width="100"/>
      <el-table-column prop="stock" label="库存" width="90"/>
      <el-table-column label="状态" width="120">
        <template #default="{ row }">
          <el-tag :type="row.status == 1 ? 'success' : 'info'">{{ row.status == 1 ? '启用' : '禁用' }}</el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="updateTime" label="更新时间" min-width="180"/>
      <el-table-column label="操作" width="160" fixed="right">
        <template #default="{ row }">
          <el-button type="primary" link @click="openEdit(row)">修改</el-button>
          <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog v-model="dialogVisible" :title="isEdit ? '修改商品' : '添加商品'" width="600px">
      <el-form :model="form" label-width="100px">
        <el-form-item label="名称">
          <el-input v-model="form.name" placeholder="请输入商品名称"/>
        </el-form-item>
        <el-form-item label="图片地址">
          <el-input v-model="form.image" placeholder="请输入图片URL"/>
        </el-form-item>
        <el-form-item label="分类ID">
          <el-input v-model.number="form.categoryId" placeholder="请输入分类ID"/>
        </el-form-item>
        <el-form-item label="价格">
          <el-input v-model.number="form.price" placeholder="请输入价格"/>
        </el-form-item>
        <el-form-item label="原价">
          <el-input v-model.number="form.originalPrice" placeholder="请输入原价"/>
        </el-form-item>
        <el-form-item label="库存">
          <el-input v-model.number="form.stock" placeholder="请输入库存"/>
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="form.status" active-value="1" inactive-value="0"/>
        </el-form-item>
        <el-form-item label="标签">
          <el-input v-model="form.tag" placeholder="请输入标签"/>
        </el-form-item>
        <el-form-item label="商家ID">
          <el-input v-model.number="form.merchantId" placeholder="请输入商家ID"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input type="textarea" :rows="4" v-model="form.description" placeholder="请输入商品描述"/>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { list, addProduct, editProduct, deleteProduct } from '@/api/product'

const loading = ref(false)
const productList = ref([])

const dialogVisible = ref(false)
const isEdit = ref(false)
const form = reactive({
  productId: null,
  name: '',
  categoryId: null,
  price: null,
  originalPrice: null,
  stock: null,
  status: 1,
  image: '',
  description: '',
  tag: '',
  merchantId: null
})

const resolveList = (data) => {
  if (Array.isArray(data)) return data
  if (Array.isArray(data?.data)) return data.data
  if (Array.isArray(data?.list)) return data.list
  return []
}

const fetchList = async () => {
  loading.value = true
  try {
    const data = await list()
    productList.value = resolveList(data)
  } catch (e) {
    ElMessage.error('获取商品列表失败')
  } finally {
    loading.value = false
  }
}

onMounted(fetchList)

const openAdd = () => {
  Object.assign(form, {
    productId: null,
    name: '',
    categoryId: null,
    price: null,
    originalPrice: null,
    stock: null,
    status: 1,
    image: '',
    description: '',
    tag: '',
    merchantId: null
  })
  isEdit.value = false
  dialogVisible.value = true
}

const openEdit = (row) => {
  Object.assign(form, row)
  isEdit.value = true
  dialogVisible.value = true
}

const handleSubmit = async () => {
  loading.value = true
  try {
    const apiRes = isEdit.value ? await editProduct({ ...form }) : await addProduct({ ...form })
    if (apiRes === null) {
      ElMessage.error(isEdit.value ? '修改失败' : '添加失败')
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '添加成功')
    dialogVisible.value = false
    await fetchList()
  } catch (e) {
    ElMessage.error('提交失败')
  } finally {
    loading.value = false
  }
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确定删除该商品吗？', '提示', { type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' })
    const res = await deleteProduct(row.productId)
    if (res !== null) {
      ElMessage.success('删除成功')
      productList.value = productList.value.filter(item => item.productId !== row.productId)
    } else {
      ElMessage.error('删除失败')
    }
  } catch (e) {
    // 用户取消
  }
}

const resolveImage = (src) => {
  if (!src) return ''
  return src.startsWith('http') ? src : src
}
</script>

<style scoped lang="scss">
.product-manage {
  padding: 16px;
}
.toolbar {
  margin-bottom: 12px;
}
</style>